package com.jinzhi.jinzhidata.controller;

import com.jinzhi.jinzhidata.util.JwtUtil;
import com.jinzhi.jinzhidata.dataobject.Order;
import com.jinzhi.jinzhidata.dataobject.Resource;
import com.jinzhi.jinzhidata.dataobject.User;
import com.jinzhi.jinzhidata.enums.ResultEnum;
import com.jinzhi.jinzhidata.service.OrderService;
import com.jinzhi.jinzhidata.service.ResourceService;
import com.jinzhi.jinzhidata.service.UserService;
import com.jinzhi.jinzhidata.util.*;
import com.jinzhi.jinzhidata.vo.ResultVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @description
 * @date 2020-01-03 16:52
 **/
@RequestMapping("/order")
@Controller
public class OrderController {

    @Autowired
    ResourceService resourceService;

    @Autowired
    OrderService orderService;

    @Autowired
    UserService userService;


    /**
     * 获取订单购买状态
     *
     * @param request
     * @param response
     * @param resourceId
     * @return
     */
    @GetMapping(value = "/getOrderState")
    @ResponseBody
    public ResultVO getOrderState(String resourceId, HttpServletRequest request, HttpServletResponse response) {
        String userId = JwtUtil.verifyAccessToken(request, response);
        if (StringUtils.isEmpty(userId) || StringUtils.isEmpty(resourceId)) {
            return ResultVOUtil.success("0");
        }
        Resource resource = resourceService.selectByResourceId(resourceId);
        if (resource.getResourceAuthorId().equals(userId)) {
            return ResultVOUtil.success("1");
        }
        Order order = orderService.selectOrderByUserAndGoods(userId, resourceId);
        if (null == order) {
            return ResultVOUtil.success("0");
        }
        return ResultVOUtil.success("1");
    }

    @GetMapping(value = "/pay")
    @ResponseBody
    public ResultVO payOrder(String resourceId, HttpServletRequest request, HttpServletResponse response) {
        String userId = JwtUtil.verifyAccessToken(request, response);
        if (StringUtils.isEmpty(userId)) {
            return ResultVOUtil.error(ResultEnum.NOT_LOGIN);
        }
        Resource resource = resourceService.selectByResourceId(resourceId);
        if (resource == null) {
            return ResultVOUtil.error(ResultEnum.NULL_ERROR);
        }
        if (userId.equals(resource.getResourceAuthorId())) {
            return ResultVOUtil.error(ResultEnum.SELF_RESOURCE_BOUGHT_ERROR);
        }
        User user = userService.selectUserByUserId(userId);
        if (user.getUserBalance().compareTo(resource.getResourcePrice()) < 0) {
            return ResultVOUtil.error(ResultEnum.BALANCE_LESS_THAN_ERROR);
        }
        Order order = orderService.selectOrderByUserAndGoods(userId, resourceId);
        if (order != null) {
            return ResultVOUtil.error(ResultEnum.RESOURCE_HAS_BEEN_BOUGHT_ERROR);
        }
        order = new Order();
        order.setOrderId(UUIDUtil.getUUID());
        order.setOrderUserId(userId);
        order.setOrderGoodsId(resourceId);
        order.setOrderPay(resource.getResourcePrice());
        userService.updateUserBalance(resource.getResourceAuthorId(), resource.getResourcePrice());
        userService.updateUserBalance(userId, resource.getResourcePrice().negate());
        orderService.saveOrder(order);
        return ResultVOUtil.success();
    }


//
//    /**
//     * 微信支付回调
//     *
//     * @param printWriter
//     * @param inputStream
//     * @return
//     */
//    @PostMapping(value = "/payCallback")
//    public void payCallBack(PrintWriter printWriter, InputStream inputStream) {
//        if (null == inputStream) {
//            printWriter.write("<xml><return_code><![CDATA[FAIL]]></return_code></xml>");
//            printWriter.close();
//            return;
//        }
//        try {
//            String resultStr;
//            int buffer_size = 1024;
//            ByteArrayOutputStream outStream = new ByteArrayOutputStream();
//            int count;
//            byte[] tempBytes = new byte[buffer_size];
//            while (true) {
//                if ((count = inputStream.read(tempBytes, 0, buffer_size)) == -1) {
//                    break;
//                }
//                outStream.write(tempBytes, 0, count);
//            }
//            outStream.flush();
//            //将流转换成字符串
//            resultStr = new String(outStream.toByteArray(), "UTF-8");
//            //将XML格式转化成MAP格式数据
//            Map<String, String> resultMap = WXPayUtil.xmlToMap(resultStr);
//            boolean result = false;
//            String returncode = resultMap.get("return_code");
//            if (returncode != null && returncode.equals("SUCCESS")) {
//                result = WXPayUtil.isSignatureValid(resultMap, Constant.WX_KEY, WXPayConstant.SignType.MD5);
//            }
//            if (result) {
//                String orderId = resultMap.get("attach");
//                Order order = orderService.selectOrderByOrderId(orderId);
//                order.setOrderTransactionId(resultMap.get("transaction_id"));
//                order.setOrderPayType(resultMap.get("bank_type"));
//                order.setOrderPay(new BigDecimal(resultMap.get("cash_fee")).multiply(new BigDecimal(100)));
//                System.out.println("实际支付金额：" + new BigDecimal(resultMap.get("cash_fee")));
//                Date date = DateUtil.formatString(resultMap.get("time_end"), "yyyyMMddhhmmss");
//                // 把订单状态设置为已支付
//                order.setOrderState("1");
//                User ret;
//                Resource resource = resourceService.selectByResourceId(order.getOrderGoodsId());
//                if (null == resource) {
//                    printWriter.write("<xml><return_code><![CDATA[FAIL]]></return_code></xml>");
//                    printWriter.close();
//                    return;
//                }
//                // 增加上传者积分
//                String authorId = resource.getResourceAuthorId();
//                User author = userService.selectUserByUserId(authorId);
//                ret = userService.updateUserBalance(authorId, author.getUserBalance().add(order.getOrderPay()));
//                if (ret == null) {
//                    printWriter.write("<xml><return_code><![CDATA[FAIL]]></return_code></xml>");
//                    printWriter.close();
//                    return;
//                }
//                Order retOrder = orderService.saveOrder(order);
//                if (retOrder == null) {
//                    printWriter.write("<xml><return_code><![CDATA[FAIL]]></return_code></xml>");
//                    printWriter.close();
//                    return;
//                }
//                printWriter.write("<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>");
//                printWriter.close();
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//            printWriter.write("<xml><return_code><![CDATA[FAIL]]></return_code></xml>");
//            printWriter.close();
//        }
//    }
}
